class player {
  constructor(board) {
    this.board = board
    this.ctx = board.ctx
    this.img = images['player']
    this.x = 100
    this.y = 300
    this.width = 70
    this.height = 70
    this.playerSpeed = 0
    this.now = 0
    this.keySpeed = 8
    this.timer = null
    this.frame()
  }
  // 得到方向
  move(fx) {
    if (fx == 'up') {
      this.up = true;
    } else if (fx == 'down') {
      this.down = true
    } else if (fx == 'left') {
      this.left = true
    } else if (fx == 'right') {
      this.right = true
    }
  }

  unset_move(fx) {
    if (fx == 'up') {
      this.up = false;
    } else if (fx == 'down') {
      this.down = false
    } else if (fx == 'left') {
      this.left = false
    } else if (fx == 'right') {
      this.right = false
    }
  }

  // 创建主机
  createPlayer() {
    this.now++
    if (this.now >= 3) {
      this.playerSpeed++
      this.now = 0
    }
    this.ctx.drawImage(this.img, 80 * (this.playerSpeed % 4), 0, 80, 80, this.x, this.y, this.width, this.height)
  }
  // 暂停
  suspend(){
    cancelAnimationFrame(this.timer)
  }
  frame() {
    this.timer = requestAnimationFrame(() => {
      this.frame()
    })
    this.createPlayer()

    // 改变主机的位置
    if (this.up) {
      if (this.y <= 0) {
        this.y = 0
      } else {
        this.y -= this.keySpeed
      }
    }
    if (this.down) {
      if (this.y >= 525) {
        this.y = 525
      } else {
        this.y += this.keySpeed
      }
    }
    if (this.left) {
      if (this.x <= 0) {
        this.x = 0
      } else {
        this.x -= this.keySpeed
      }
    }
    if (this.right) {
      if (this.x >= 880) {
        this.x = 880
      } else {
        this.x += this.keySpeed
      }
    }
  }
}

export { player }